package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.Date;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */


    public Employee login(EmployeeLoginDTO employeeLoginDTO) {

        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.selectOne(new LambdaQueryWrapper<Employee>().eq(Employee::getUsername, username));

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public void saveemployee(EmployeeDTO employeeDTO) {
        //1、创建数据库实例对象
        Employee employee =  new Employee();
        //对象复制
        BeanUtils.copyProperties(employeeDTO,employee);
        //设置状态为启用状态
        employee.setStatus(StatusConstant.ENABLE);
        //设置密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //设置创建时间和修改时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //创建当前用户的创建人ID
        employee.setCreateUser(BaseContext.getCurrentId()); //获取当前登录的用户ID
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.insert(employee);

    }

    @Override
    public IPage<Employee> listEmployee(IPage<Employee> employeeIPage, EmployeePageQueryDTO employee) {
        return employeeMapper.selectPageList(employeeIPage,employee);
    }

    @Override
    public Result startOrStop(Integer status, Long id) {
        LambdaUpdateWrapper<Employee> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Employee::getId,id);
        updateWrapper.set(Employee::getStatus,status);
        this.update(updateWrapper);
        return Result.success();


    }
    /**
     * 修改密码
     * @param map
     * //修改密码时，要判断新密码和旧密码是否相同，如果相同则不允许修改
     * //修改密码时，要判断新密码和确认密码是否相同，如果不同则不允许修改
     */

    @Override
    public void editPassword(PasswordEditDTO map) {

        // 1. 判断新密码和旧密码是否相同
        if (map.getNewPassword().equals(map.getOldPassword())) {
            throw new PasswordErrorException(MessageConstant.NEW_PASSWORD_SAME_AS_OLD);
        }

        // 2. 根据员工id修改密码
        LambdaUpdateWrapper<Employee> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Employee::getId, map.getEmpId())
                .eq(Employee::getPassword, DigestUtils.md5DigestAsHex(map.getOldPassword().getBytes()))
                .set(Employee::getPassword, DigestUtils.md5DigestAsHex(map.getNewPassword().getBytes()));

        boolean rows = this.update(updateWrapper);

        // 3. 判断旧密码是否正确（如果更新行数为0，说明旧密码不正确）
        if (rows==false) {
            throw new PasswordErrorException(MessageConstant.OLD_PASSWORD_ERROR);
        }
    }


}
